package com.qhgrain.app.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.AppVo;
import com.qhgrain.app.vo.PairVo;
import com.qhgrain.gway.util.HttpUtil;

@Service
public class ApplicationService {
	
	private static Logger LOG = LoggerFactory.getLogger(ApplicationService.class);
	
	private final static String BASE_URL = ConfigUtil.getProperties(UrlEnum.APP)+"/application";

	/**
	 * 获取所有应用，并拼成pairVo
	 * 如果参数userId是空的，则返回全部应用
	 * 如果参数userId不为空，则返回该用户所拥有的应用
	 * @param userId
	 * @return
	 * @throws Exception 
	 */
	public List<PairVo> getAll(String userId) throws Exception{
		
		List<PairVo> list = new ArrayList<PairVo>();
		JSONArray array = getAll2(userId);
		JSONObject o = null;
		for(int i = 0;i<array.size();i++){
			o = array.getJSONObject(i);
			list.add(new PairVo(o.getString("id"),o.getString("appName")));
		}
		return list;
	}
	
	public List<AppVo> getAll3(String userId)throws Exception{
		return JSONArray.parseArray(getAll2(userId).toJSONString(), AppVo.class);
	}
	/**
	 * 获取所有应用
	 * 如果参数userId是空的，则返回全部应用
	 * 如果参数userId不为空，则返回该用户所拥有的应用
	 * @param userId
	 * @return
	 * @throws Exception 
	 */
	public JSONArray getAll2(String userId) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		if(StringUtil.isNotBlank(userId)){
			map.put("userId", userId);
		}
		try {
			String vo = HttpUtil.get(BASE_URL+"/get/all", map);
			JSONObject voJson = JSONObject.parseObject(vo);
			if("200".equals(voJson.getString("state"))){
				
				JSONArray array = voJson.getJSONArray("data");
				
				return array;
			}else{
				throw new RuntimeException("api获取所有应用list,api出错...."+vo);
			}
		} catch (Exception e) {
			LOG.error("获取所有应用出错...",e);
			throw e;
		}
	}
	/**
	 * 根据应用群组id获取对应的所有应用
	 * @param appGroupId
	 * @return
	 * @throws Exception 
	 */
	public List<PairVo> queryByAppGroup(String appGroupId) throws Exception{
		List<PairVo> list = new ArrayList<PairVo>();
		JSONArray array = queryByAppGroup2(appGroupId);
		JSONObject o = null;
		for(int i = 0;i<array.size();i++){
			o = array.getJSONObject(i);
			list.add(new PairVo(o.getString("id"),o.getString("appName")));
		}
		return list;
	}
	/**
	 * 根据应用群组id获取对应的所有应用
	 * @param appGroupId
	 * @return
	 * @throws Exception 
	 */
	public JSONArray queryByAppGroup2(String appGroupId) throws Exception{
		try {
			String vo = HttpUtil.get(BASE_URL+"/get/by/appgroup/"+appGroupId, new HashMap<String,String>());
			JSONObject voJson = JSONObject.parseObject(vo);
			if("200".equals(voJson.getString("state"))){
				return voJson.getJSONArray("data");
			}else{
				LOG.error("根据应用群组id获取对应的所有应用,api失败。。。"+vo);
				throw new RuntimeException("根据应用群组id获取对应的所有应用,api失败。。。"+vo);
			}
		} catch (Exception e) {
			LOG.error("根据应用群组id获取对应的所有应用失败。。。",e);
			throw e;
		}
		
	}
	
	public AppVo find(String id) throws IOException{
		String vo = HttpUtil.get(BASE_URL+"/get/"+id, new HashMap<String,String>());
		JSONObject voJson = JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			return JSONObject.parseObject(voJson.getString("data"),AppVo.class);
		}else{
			LOG.error("根据appId从api获取应用信息信息失败..."+voJson);
			throw new RuntimeException("根据appId从api获取应用信息信息失败..."+voJson);
		}
	}
	
	public AppVo findByAppCode(String appCode)throws IOException{
		Map<String,String> map = new HashMap<String,String>();
		map.put("appCode", appCode);
		String vo = HttpUtil.get(BASE_URL+"/getByAppCode",map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONObject.parseObject(voJson.getString("data"), AppVo.class);
		}else{
			LOG.error("根据appCode从api获取对象信息失败...appCode="+appCode+"...vo="+vo);
			throw new RuntimeException("根据appCode从api获取对象信息失败...appCode="+appCode+"...vo="+vo);
		}
		
	}
	
	/**
	 * 根据角色获取应用
	 * @param roleId
	 * @return
	 * @throws IOException
	 */
	public List<AppVo> queryByRole(String roleId) throws IOException{
		if(StringUtil.isBlank(roleId)){
			throw new RuntimeException("roleId不能为空");
		}
		String vo = HttpUtil.get(BASE_URL+"/queryByRole/"+roleId);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONArray.parseArray(voJson.getString("data"), AppVo.class);
		}else{
			LOG.error("根据roleId从api获取应用对象信息失败...roleId="+roleId+"...vo="+vo);
			throw new RuntimeException("根据roleId从api获取应用对象信息失败...roleId="+roleId+"...vo="+vo);
		}
	}
	/**
	 * 保存角色-应用的关联关系（会将就关联全部删除）
	 * @param roleId
	 * @param appIds
	 * @throws  
	 */
	public void saveRoleApplication(String roleId,List<String> appIds) throws IOException{
		if(StringUtil.isBlank(roleId)){
			throw new RuntimeException("roleId不能为空");
		}
		String appIdString = "";
		if(appIds != null && appIds.size()>0){
			appIdString = StringUtils.join(appIds,",");
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("roleId", roleId);
		map.put("appIds", appIdString);
		
		String vo = HttpUtil.post(BASE_URL+"/saveRoleApplication", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			
		}else{
			LOG.error("保存角色-应用关联关系，api失败...vo="+vo);
			throw new RuntimeException("保存角色-应用关联关系，api失败...vo="+vo);
		}
	}
}
